package buddyStrings;

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public boolean buddyStrings(String s, String goal) {
        // 如果s == goal
        // 判断s中是否有相同的字符串
        if(s.length()!=goal.length())return false;
        if(s.equals(goal)) {
            Set<Character> set = new HashSet<>();
            for (int i = 0; i < s.length(); i++) {
                if(!set.add(s.charAt(i))) {
                    return true;
                }
            }
            return false;
        }
        // 如果s!=goal
        // 判断s和goal的不同的个数 == 2
        int i = 0;
        while (i<s.length()) {
            if(s.charAt(i)==goal.charAt(i))i++;
        }
        int j = s.length()-1;
        while (j>=0) {
            if(s.charAt(j)==goal.charAt(j))j--;
        }
        char[] chars = s.toCharArray();
        char c = chars[i];
        chars[i] = chars[j];
        chars[j] = c;
        return new String(chars).equals(goal);
    }
}
